<template>
  <a-drawer
    v-model:visible="isDrawer"
    :width="width"
    :title="title"
    unmountOnClose
    placement="right"
    ok-text="提交"
    :ok-loading="subLoading"
    :on-before-ok="formSubmit"
    @cancel="handleReset"
  >
    <a-form :model="formParams" :rules="rules" ref="formRef" label-placement="left">
      <a-form-item label="上级区域" field="parentId">
        <a-tree-select
          :fieldNames="{
            key: 'id',
            title: 'regionName',
          }"
          :data="getRegionTreeList"
          :treeProps="{
            virtualListProps: {
              height: 350,
            },
          }"
          :fallback-option="fallback"
          v-model="formParams.parentId"
          placeholder="请选择区域，省份无需选择"
        />
      </a-form-item>

      <a-form-item label="区域名称" field="regionName">
        <a-input placeholder="请输入区域名称" v-model="formParams.regionName" />
      </a-form-item>

      <a-form-item label="区域编码" field="regionCode">
        <a-input placeholder="请输入区域编码" v-model="formParams.regionCode" />
      </a-form-item>

      <a-form-item label="显示排序" field="regionOrders">
        <a-input-number placeholder="显示排序" v-model="formParams.regionOrders" class="w-full" />
      </a-form-item>

      <a-row :gutter="12">
        <a-col :span="12">
          <a-form-item
            label="是否省份"
            field="isProinve"
            :label-col-props="{ span: 10 }"
            :wrapper-col-props="{ span: 14 }"
          >
            <a-switch v-model="formParams.isProinve" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item
            label="是否城市"
            field="isCity"
            :label-col-props="{ span: 10 }"
            :wrapper-col-props="{ span: 14 }"
          >
            <a-switch v-model="formParams.isCity" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="12">
        <a-col :span="12">
          <a-form-item
            label="是否区县"
            field="isDistrict"
            :label-col-props="{ span: 10 }"
            :wrapper-col-props="{ span: 14 }"
          >
            <a-switch v-model="formParams.isDistrict" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item
            label="是否启用"
            field="isEnable"
            :label-col-props="{ span: 10 }"
            :wrapper-col-props="{ span: 14 }"
          >
            <a-switch v-model="formParams.isEnable" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { Message, TreeNodeData } from '@arco-design/web-vue';
  import type { formParamsType } from './types';

  import { addRegion, editRegion, regionInfo } from '@/api/system/region';

  const rules = {
    regionName: {
      required: true,
      message: '区域名称不能为空',
      trigger: 'blur',
    },
    regionCode: {
      required: true,
      message: '区域编码不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);

  const props = defineProps({
    title: {
      type: String,
      default: '添加区域',
    },
    width: {
      type: Number,
      default: 450,
    },
    regionList: {
      type: Array as PropType<TreeNodeData[]>,
    },
  });

  const getRegionTreeList = computed(() => {
    return props.regionList;
  });

  const fallback = (key) => {
    return {
      key,
      title: `顶级区域`,
    };
  };

  const defaultValueRef = () => ({
    id: undefined,
    isCenterCity: false,
    isProinve: false,
    isCity: false,
    isDistrict: false,
    isEnable: true,
    parentId: undefined,
    regionCode: '',
    regionName: '',
    regionOrders: undefined,
  });

  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

  const formParams = ref<formParamsType>(defaultValueRef());

  function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit(done) {
    formRef.value.validate((errors) => {
      if (errors) {
        Message.error('请填写完整信息');
        subLoading.value = false;
        return done(false);
      }
      if (formParams.value.id) {
        editRegion(formParams.value)
          .then((_) => {
            Message.success('编辑成功');
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      } else {
        addRegion(formParams.value)
          .then((_) => {
            Message.success('添加成功');
            emit('change');
            handleReset();
            return done(true);
          })
          .catch(() => {
            return done(false);
          });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    regionInfo({ id: formParams.value.id }).then((res) => {
      const info = {
        id: res.id,
        isCenterCity: res.isCenterCity,
        isProinve: res.isProinve,
        isCity: res.isCity,
        isDistrict: res.isDistrict,
        isEnable: res.isEnable,
        parentId: res.parentId,
        regionCode: res.regionCode,
        regionName: res.regionName,
        regionOrders: res.regionOrders,
      };
      formParams.value = info;
      isDrawer.value = true;
    });
  }

  onMounted(() => {});

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
